<?php
class ImagesController extends AppController {

	var $name = 'Images';
	var $helpers = array('Html','Form','Accessibility','Pagination', 'Associations','Input');
	var $uses = array('Image','Configuration');
	var $components = array('Upload');


	function upload($album_id = null) {
		// Retrieving organization's data
		$this->set('album_id', $album_id);
		$organization = $this->othAuth->getData('organization');
		$title = 'Adicionar imagem';
		$this->set('title', $title);
		$this->set('pageTitle', $title);
					
		if (empty($this->data)) {
			if(!$album_id) {
				// Redirecting to File List
				$_SESSION['mensagem']['error'][] = 'Álbum inválido!';  
				$this->redirect('/webs/albuns');
			}



			$this->data['Image']['album_id'] = $album_id;
		} else {
			if ($this->data['Image']['File']['error'] == 4) {
				// Redirecting to File List
				$_SESSION['mensagem']['error'][] = 'Adicione uma foto';  
				return;
			}
			if (is_uploaded_file($this->data['Image']['File']['tmp_name'])) {
				/* checking quota */
				$sum = $this->Image->find('all', array('fields'=>array('SUM(tamanho) AS total_sum'),
			                                      'conditions'=>array('Image.organization_id'=>$organization['id']),
			                                      'recursive'=>-1));
				$used = ($sum[0][0]['total_sum']);

				$configuration_quota = $this->Configuration->find('first', array('conditions'=>array('name'=>'download_quota')));
				$quota = ($configuration_quota['Configuration']['value']);

				if (($used + $this->data['Image']['File']['size']) > $quota) {
					$_SESSION['mensagem']['error'][] = 'Quota estourada.';
				}
					
				$file = $this->data['Image']['File'];

				// Retrieving data from uploaded file
				$size = $this->data['Image']['File']['size'];
					
				// Getting file extension
				$extensions = explode(".",$this->data['Image']['File']['name']);
				$extension = $extensions[sizeof($extensions)-1];


				// Generating file's path and name
				$path = '/cms/'.$organization['id'];
				$filename = $this->data['Image']['File']['name'].'.'.$extension;

				// set the upload destination folder
				$destination = realpath('../../app/webroot/') . $path.'/';

				// 	Creating folder for organization
				if(!is_dir($destination)) {
					mkdir($destination, 0777);
				}

				if (!isset($_SESSION['mensagem']['error'])) {
					// upload the image using the upload component
					$result = $this->Upload->upload($file, $destination, $this->data['Image']['File']['name'], NULL, array('*'));

					// Creating information about created file
					//$this->data['Image']['type'] = $this->data['Image']['File']['type'];
					$this->data['Image']['tamanho'] = $this->data['Image']['File']['size'];
					$this->data['Image']['filename'] = $path."/".$this->data['Image']['File']['name'];
					//$this->data['Image']['data'] 				= $fileData;
					$this->data['Image']['organization_id'] = $organization['id'];

					// Saving information on database
					$this->Image->save($this->data);

					// Redirecting to File List
					$_SESSION['mensagem']['success'][] = 'Imagem adicionada com sucesso!';
					$this->redirect('/albums/view/'.$this->data['Image']['album_id']);
				}
			} else {
				// Display "Invalid File" error message
			}
		}

	}


	function show($id) {
		if(!$id) {
			// Redirecting to File List
			$_SESSION['mensagem']['error'][] = 'Imagem inválida!'; 
			$this->redirect('/webs/albuns');
		}

		$title = 'Visualizar imagem';
		$this->set('title', $title);
		$this->set('pageTitle', $title);

		$this->Image->id = $id;
		$image = $this->Image->read();
		$this->set('image',$image);
	}


	function edit($id) {
		if (!$id) {
			$this->redirect('/webs/albuns');
		}

		$this->set('pageTitle','Editar Imagem');
		$this->Image->id = $id;

		if (empty($this->data)) {
			$this->data = $this->Image->read();
		} else {

			if ($this->Image->save($this->data['Image'])) {
				$_SESSION['mensagem']['success'][] = 'Foto alterada com sucesso!';
			} else {
				$_SESSION['mensagem']['error'][] = 'Erro ao tentar alterar a Foto.';
			}
			$this->redirect('/images/show/'.$id);
		}
		$image = $this->Image->find(array('`Image`.id' => $id));
		$this->set('image', $image);
	}

	function delete($id=NULL) {
		if (!$id) $this->redirect('/webs/albuns');

		$image = $this->Image->find(array('`Image`.id' => $id));
		$path = $image['Image']['filename'];
		$album_id = $image['Image']['album_id'];
		$destination = realpath('../../app/webroot/') . $path;

		if ($this->Image->del($id)) {
			if (unlink($destination)) {
				$_SESSION['mensagem']['success'][] = 'Imagem excluida com sucesso!';

			} else {
				$_SESSION['mensagem']['error'][] = 'Erro ao tentar excluir a imagem.';
			}
		} else {
			$_SESSION['mensagem']['error'][] = 'Erro ao tentar excluir a imagem.';
		}
		$this->redirect('/albums/view/'.$album_id);
	}



}

